package flutter.plugins.screen.screen;

import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.lang.reflect.Field;

import static android.content.Context.WINDOW_SERVICE;

public class CallingInReceiver extends BroadcastReceiver {
  public static String ACTION_CALLING_IN = "flutter.plugins.screen.screen.ACTION_CALLING_IN";
  public static String ACTION_CALL_CONNECTED = "flutter.plugins.screen.screen.ACTION_CALL_CONNECTED";
  public static String ACTION_CALL_STATE_CHANGE = "flutter.plugins.screen.screen.ACTION_CALL_STATE_CHANGE";
  public static String ACTION_CALLINGINUI_FINISH = "flutter.plugins.screen.screen.ACTION_CALLINGINUI_FINISH";
  private static String TAG = "CallingInReceiver";

  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if(action == ACTION_CALLING_IN) {
      String name = intent.getStringExtra("name");
      String tips = intent.getStringExtra("tips");
      Log.i(TAG, "name:"+name);
      Log.i(TAG, "tips:"+tips);
      startActivity(context, name, tips);
    }

    if(action == ACTION_CALL_CONNECTED) {
      finishActivity(context);
    }
  }

  private void startActivity(Context context, String name, String tips) {
    //管理锁屏的一个服务
    KeyguardManager km = (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
    if (km.inKeyguardRestrictedInputMode()) {
      //判断是否锁屏
      Intent alarmIntent = new Intent(context, CallintInUIActivity.class);
      //在广播中启动Activity的context可能不是Activity对象，所以需要添加NEW_TASK的标志，否则启动时可能会报错。
      alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      alarmIntent.putExtra("name", name);
      alarmIntent.putExtra("tips", tips);
      if(Build.VERSION.SDK_INT >= 26){
        alarmIntent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
      }
      context.startActivity(alarmIntent); //启动显示锁屏消息的activity
    } else {
      showSystemAlert(context, name, tips);
    }
  }

  private void finishActivity(Context context) {
    Intent finishIntent = new Intent();
    finishIntent.setAction(ACTION_CALLINGINUI_FINISH);
    context.sendBroadcast(finishIntent);

    if(systemAlertView != null && mWindowManager != null) {
      removeSystemAlert();
    }
  }


  private LinearLayout systemAlertView;
  private WindowManager mWindowManager;

  private void showSystemAlert(Context context, String name, String tips) {
    mWindowManager = (WindowManager)context.getSystemService(WINDOW_SERVICE);
    systemAlertView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.calling_in_ui, null);

    DisplayMetrics metrics = new DisplayMetrics();
    mWindowManager.getDefaultDisplay().getMetrics(metrics);

    WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
    } else {
      mLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
    }

    mLayoutParams.format = PixelFormat.RGBA_F16;
    mLayoutParams.gravity = Gravity.CENTER;  //窗口位置
    mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_FULLSCREEN;
    mLayoutParams.width = metrics.widthPixels;
    mLayoutParams.height = metrics.heightPixels;

    mWindowManager.addView(systemAlertView, mLayoutParams);

    initSystemAlertView(context, name, tips);
  }

  private void removeSystemAlert() {
    mWindowManager.removeViewImmediate(systemAlertView);
    systemAlertView = null;
  }



  private void initSystemAlertView(final Context context, String name, String tips) {

    TextView nameTxt = systemAlertView.findViewById(R.id.name);
    nameTxt.setText(name);

    TextView tipTxt = systemAlertView.findViewById(R.id.tips);
    tipTxt.setText(tips);

    systemAlertView.findViewById(R.id.reject).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        reject(context);
        removeSystemAlert();
      }
    });

    systemAlertView.findViewById(R.id.accept).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        accept(context);
        removeSystemAlert();
      }
    });
  }

  private void reject(Context context) {
    Intent intent = new Intent();
    intent.setAction(CallingInReceiver.ACTION_CALL_STATE_CHANGE);
    intent.putExtra("state", "reject");
    context.sendBroadcast(intent);
  }

  private  void accept(Context context) {
    Intent intent = new Intent();
    intent.setAction(CallingInReceiver.ACTION_CALL_STATE_CHANGE);
    intent.putExtra("state", "accept");
    context.sendBroadcast(intent);
  }
}
